<template>
  <div>
    <el-card class="mb-10">
      <CategorySelector :disabled="isEdit"></CategorySelector>
    </el-card>
    <el-card>
      <!-- 列表展示 -->
      <div v-show="!isEdit">
        <!-- <el-button type="primary" :icon="Plus" :disabled="!categoryStore.category3Id" @click="isEdit = true">添加属性</el-button> -->
        <el-button class="mb-10" type="primary" :icon="Plus" @click="isEdit = true" >添加属性</el-button>

        <el-table :data="attrList" border>
          <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
          <el-table-column label="属性名" property="attrName" width="160"></el-table-column>
          <el-table-column label="属性值列表">
            <template #default="{ row, $index }">
              <el-tag class="mr-10" type="success" v-for="attrVal in row.attrValueList">
                {{ attrVal.valueName }}
              </el-tag>
              
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140">
            <template #default="{ row, $index }">
              <el-button type="warning" :icon="Edit" size="small" title="修改" @click="editAttr(row)"></el-button>
              
              <el-popconfirm :title="`确认要删除[${ row.attrName }]吗?`" @confirm="deleteAttr(row)">
                <template #reference>
                  <el-button type="danger" :icon="Delete" size="small" title="删除"></el-button>
                </template>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 编辑模式 -->
      <div v-show="isEdit">
        <el-form :inline="true">
          <el-form-item label="属性名">
            <el-input v-model="attrForm.attrName" placeholder="输入属性名"></el-input>
          </el-form-item>
        </el-form>
        <div class="mb-10">
          <el-button type="primary" :disabled="!attrForm.attrName" @click="addAttrVal">添加属性值</el-button>
          <el-button @click="onCancelSave">取消</el-button>
        </div>
        <el-table :data="attrForm.attrValueList" border class="mb-10">
          <el-table-column type="index" label="序号" width="80"></el-table-column>
          <el-table-column label="属性值名称">
            <template #default="{ row, $index }">
              <!-- <div>{{ row.valueName }}</div> -->
              <el-input v-if="row.inputVisible" ref="inputRef" type="text" v-model="row.valueName" size="small" @blur="inputBlur(row, $index)" />
              <div v-else @click="inputFocus(row)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ row, $index }">
              <el-popconfirm :title="`确定要删除[${ row.valueName }]吗?`" @confirm="removeAttrVal(row, $index)">
                <template #reference>
                  <el-button type="danger" :icon="Delete" size="small" title="删除"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div>
          <el-button type="primary" :disabled="!(attrForm.attrName && attrForm.attrValueList.length)" @click="onSave">保存</el-button>
          <el-button @click="onCancelSave">取消</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { Plus, Delete, Edit } from '@element-plus/icons-vue'
import { useCategoryStore } from '@/stores/category'
import attrApi, { type AttrModel, type AttrValueModel } from '@/api/attr'
import { watch, ref ,nextTick } from 'vue';
import { ElMessage, type InputInstance } from 'element-plus';
import { cloneDeep } from 'lodash';

const categoryStore = useCategoryStore();
// 切换编辑状态
const isEdit = ref(false); 

// 新增收集数/编辑回显数据
const initAttrForm = () => ({
  attrName: '',
  attrValueList: [],
  categoryId: undefined, 
  categoryLevel: 3
})
const attrForm = ref<AttrModel>(initAttrForm())

// 添加属性值回调
const addAttrVal = () => {
  attrForm.value.attrValueList.push({
    valueName: '', 
    inputVisible: true
  
  })
}
// 删除属性值回调
const removeAttrVal = (row: AttrValueModel, index: number) => {
  attrForm.value.attrValueList.splice(index, 1);
}

// 编辑回显数据
const editAttr = (row: AttrModel) => {
  attrForm.value = cloneDeep(row);
  isEdit.value = true; 
}

// 保存
const onSave = async () => {
  if ( !(attrForm.value.attrName && attrForm.value.attrValueList.length) ) {
    ElMessage.error('[属性名] 和 [属性值列表] 必须有值');
    return
  }
  // 给保存的数据赋 分类的id 值
  if (!attrForm.value.categoryId) {
    attrForm.value.categoryId = categoryStore.category3Id;
  }
 
  try {
    await attrApi.save(attrForm.value);
    ElMessage.success('保存成功'); 
    onCancelSave(); 
    getList(); 
  } catch (error) {
    console.error(error);
    ElMessage.error('保存失败');
  }
}

// 取消
const onCancelSave = () => {
  attrForm.value = initAttrForm();
  isEdit.value = false;
}
// 删除主界面数据
const deleteAttr = async (row: AttrModel) => {
  try {
    await attrApi.delete(row.id as number);
    ElMessage.success('删除成功'); 
    getList(); 
  } catch (error) {
    console.error(error);
    ElMessage.error('删除失败');
  }
}





// 展示
const attrList = ref<AttrModel[]>();
// 获取
const getList = async () => {
  try {
    const { category1Id, category2Id, category3Id } = categoryStore;
    let result = await attrApi.getAttrInfoList(category1Id as number, category2Id as number, category3Id as number);
    attrList.value = result;
  } catch (error) {
    console.error(error);
    ElMessage.error('获取平台属性列表失败');
  }
}
//监控
watch(() => categoryStore.category3Id, async (nval) => {
  
  if (!nval) {
    attrList.value = []
    return
  }
  getList();
}, { immediate: true })



const inputRef=ref<InputInstance>();
nextTick(()=>{
  inputRef.value?.focus();
})
//inputBlur 与inputFocus
const inputBlur=(row:AttrValueModel,index:number)=>{
  //失焦时
  //1-如果有值就切换显示div ,
  //2-没有值就把之前添加到数据去除
  if(row.valueName){
    const isRepate=attrForm.value.attrValueList.some((item,idx)=>{
      if(idx !=index){
        return item.valueName == row.valueName
      }
    });
    if(isRepate){
      ElMessage.error("输入的属性值重复，请重试");
      attrForm.value.attrValueList.splice(index,1);
      return;
    };
    row.inputVisible=false;
  }else {
    attrForm.value.attrValueList.splice(index,1)
  }
};
const inputFocus=(row:AttrValueModel)=>{
  //1-显示输入框 2-聚焦
  row.inputVisible=true;
  nextTick(()=>{
    inputRef.value?.focus();
  })
}

</script>

<style scoped>

</style>